package com.meihua.shellapp.base;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.shellapp.R;
import com.meihua.shellapp.activity.login.LoginActivity;
import com.meihua.shellapp.activity.webview.WebActivity;
import com.meihua.shellapp.bean.AuthResult;
import com.meihua.shellapp.bean.PayResult;
import com.meihua.shellapp.common.Constant;
import com.meihua.shellapp.dialog.LoginandRegistrationDialog;
import com.meihua.shellapp.dialog.ToastDialog;
import com.meihua.shellapp.utils.LogUtils;
import com.meihua.shellapp.utils.SharedPreferencesUtil;
import com.meihua.shellapp.utils.ToastUtils;
import com.meihua.shellapp.utils.URL;
import com.meihua.shellapp.utils.UrlUtils;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;
import okio.Utf8;

/**
 * Created by ${zhangyuanchao} on 2017/10/18.
 */

public abstract class BaseWebViewActivity extends BaseActivity {
    public WebView mWebView;
    private LoginandRegistrationDialog dialog;

    public void initWebView(WebView mWebView, final ProgressBar mLoading, String url, final TextView textView) {
        this.mWebView = mWebView;
        WebSettings settings = mWebView.getSettings();
        mWebView.loadUrl(url);
        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setDefaultTextEncodingName("utf-8");
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        settings.setDomStorageEnabled(true);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        // 设置允许JS弹窗
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                /*设置页面标题*/
                textView.setText(title);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                final ToastDialog toastDialog = new ToastDialog(BaseWebViewActivity.this, R.style.userinfo_sex_Dialog, message);
                toastDialog.setOnDialogToastListener(new ToastDialog.OnDialogToastListener() {
                    @Override
                    public void okClick() {
                        result.confirm();
                        toastDialog.dismiss();
                    }
                });
                toastDialog.show();
                return true;
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (null == mLoading) return;
                if (newProgress < 100) {
                    mLoading.setProgress(newProgress);
                } else {
                    mLoading.setVisibility(View.GONE);
                }
            }
        });

        //监听网页的加载操作
        mWebView.setWebViewClient(new WebViewClient() {
            //设置不用系统浏览器打开,直接显示在当前Webview
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.getInstance().e("Override: " + url);
                if (url.contains("alipays://platformapi/startApp?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.contains("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.contains(URL.getUrl().HOST + "/index.php?m=&c=Login&a=ok")) {
                    Intent intent = new Intent(BaseWebViewActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                    return true;
                }

                if ((url.contains("https://sky.zhongan.com/iybsky/view/m/product/estimate/tips.html")
                        || url.contains("https://m.iyunbao.com/mobile/insurances/51255824/insure")
                ||url.contains("https://mhealth.zhongan.com/health/iYunBao/common/tips.html"))
                        && !SharedPreferencesUtil.getInstance().getBoolean(BaseWebViewActivity.this, Constant.ISLOGIN, false)) {
                    dialog = new LoginandRegistrationDialog.Builder(BaseWebViewActivity.this)
                            .setClickSure(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(BaseWebViewActivity.this, LoginActivity.class);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setClickCencle(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(BaseWebViewActivity.this, WebActivity.class).putExtra("url", URL.getUrl().REGISTER_URL));
                                    dialog.dismiss();
                                }
                            })
                            .setMessage("请您登录注册！")
                            .show();
                    return true;
                }

                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                super.onReceivedSslError(view, handler, error);
                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                handler.proceed();
            }
        });
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private void payByAlipay(String info) {

        //缺少加签的步骤

        final String orderInfo = info;   // 订单信息
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(BaseWebViewActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(BaseWebViewActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(BaseWebViewActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(BaseWebViewActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(BaseWebViewActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (null == mWebView) return;
        mWebView.resumeTimers();
    }

    @Override
    protected void onPause() {
        super.onPause();
        /*暂停全局*/
        if (null == mWebView) return;
        mWebView.pauseTimers();
    }

    @Override
    protected void onDestroy() {
        if (null == mWebView) return;
        /*清除缓存 历史记录*/
        mWebView.clearCache(true);
        mWebView.clearHistory();
        /*销毁*/
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (null == mWebView) return false;
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
